package com.share.example.selenium.service.hzhc.task_v2;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.share.common.utils.DelayUtil;
import com.share.common.utils.HttpUtil;
import com.share.example.selenium.model.hzhc.task_v2.HmTask;
import com.share.example.selenium.model.hzhc.task_v2.TaskV2UserInfo;
import com.share.example.selenium.service.AbsDriver;
import com.share.example.selenium.utils.DriverUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Data
@Slf4j
@Service
public class HcxxTask_v2LoginService extends AbsDriver {
    private final String TASK_INDEX_URL_PRE = "https://project.jfkjkg.com/#/web";

    @Autowired
    protected WebDriver driver;

    @Override
    public void reInitDriver(WebDriver driver) {
        this.driver = driver;
    }

    //打开任务系统的首页
    public TaskV2UserInfo toTaskHomePage() {
        //1.打开首页
        String url = "https://mh.ihanchen.com/#/appCenter/index";
        driver.get(url);

        //内部数据是请求接口获取的，导致下面的元素定位必须要等待
        DelayUtil.sleepSecond(10);

        String hmTarget = driver.getWindowHandle();

        //2.点击工时项目管理----貌似无法打开
        WebElement appcenter = driver.findElement(By.xpath("/html/body/div/div/section/section/main/div/div[2]/div/div/div/div/div[2]/div/div[1]/div[2]/div[4]/div"));
        appcenter.click();

//        String token = (String) JSONPath.read(hmUserInfo, "token");
//        String redirection = URLEncoder.encode("https://project.jfkjkg.com/");
//        String forwordUrl = "https://project.jfkjkg.com/#/oAuth2?redirection=" + redirection + "&ticket=" + token;
//        driver.get(forwordUrl);

        DelayUtil.sleepSecond(4);

        //切换到新的页面
        DriverUtil.switchToTarget(driver, null, hmTarget);
        String taskTarget = driver.getWindowHandle();

        String userInfo = DriverUtil.getLocalStorage(driver, "sword-current-user");
        String forward_currentUrl = driver.getCurrentUrl();
        if (forward_currentUrl.contains(TASK_INDEX_URL_PRE)) {
            log.info("项目管理系统---用户信息={}", userInfo);
            return JSON.parseObject(userInfo, TaskV2UserInfo.class);
        } else {
            log.info("登录失败,forward_currentUrl={}", forward_currentUrl);
            return null;
        }
    }

    public boolean addTaskLog(String token, String taskId, String workhour, String content) {
        String addTaskUrl = "https://project.jfkjkg.com/api/workhour/add";
        JSONObject body = new JSONObject();
        body.put("taskId", taskId);
        body.put("workhour", workhour);
        body.put("remark", content);
        body.put("isAdd", 1);
        //构建通用map
        Map<String, String> header = new HashMap();
        header.put("token", token);

        try {
            String post = HttpUtil.post(addTaskUrl, body.toJSONString(), header);
            String code = (String) JSONPath.read(post, "$.code");
            if ("200".equals(code)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.info("调用异常", e);
            return false;
        }
    }

    public List<HmTask> listAllTask(String token) {
        List<HmTask> reList = new LinkedList<>();
        String filterKey = "工时异常";

        String listTaskUrl = "https://project.jfkjkg.com/api/task/page";
        JSONObject body = new JSONObject();
        body.put("pageSize", 10);
        body.put("conditionVo", JSON.parseObject("{\"status\":0,\"flag\":0}"));

        //构建通用map
        Map<String, String> header = new HashMap();
        header.put("token", token);
        int totalPage = 1;
        for (int i = 1; i <= totalPage; i++) {
            try {
                int pageNum = i;
                body.put("_timestamp", System.currentTimeMillis());
                body.put("pageNum", pageNum);

                String post = HttpUtil.post(listTaskUrl, body.toJSONString(), header);
                Integer code = (Integer) JSONPath.read(post, "$.code");
                if (code != null && 200 == code) {
                    Object read = JSONPath.read(post, "$.data.data");

                    List<HmTask> tmpList = JSON.parseArray(read.toString(), HmTask.class);
                    for (HmTask item : tmpList) {
                        if (item.getTaskName().contains(filterKey) && item.getTaskTypeName().contains(filterKey)) {
                            continue;
                        }
                        reList.add(item);
                    }

                    if (i == 1) {
                        //修改分页
                        totalPage = (Integer) JSONPath.read(post, "$.data.totalPage");
                    }
                }
            } catch (Exception e) {
                log.info("调用异常", e);
            }
        }
        return reList;
    }

    public static void main(String[] args) {
        List<HmTask> task = new HcxxTask_v2LoginService().listAllTask("c0eb3a93fcf24c68bc9e52707fd032d4");
        System.out.println(JSON.toJSON(task));
    }
}
